package com.yilin.platform.base_core.application;

import com.sun.istack.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Map;

@Component
public class RedisClient implements ApplicationContextAware {
    private static ApplicationContext currentApplicationContext;
    @Autowired
    private StringRedisTemplate template;


    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        currentApplicationContext = applicationContext;
    }

    public static RedisClient getInstance() {
        return currentApplicationContext.getBean(RedisClient.class);
    }



    //------------------键值对操作------------------------------

    public Boolean exists(String key) {
        return template.hasKey(key);
    }

    public void save(String key, String value) {
        template.opsForValue().set(key, value);
    }

    public String get(String key) {
        return template.opsForValue().get(key);
    }

    public void delete(String key) {
        template.delete(key);
    }

    public void expire(String key, int i) {
        template.expire(key, Duration.ofSeconds(i));
    }

    //------------------Hash操作------------------------------

    public String hget(String key, String var) {
        return (String) template.opsForHash().get(key, var);
    }

    public void hset(String key, String field, String value) {
        template.opsForHash().put(key, field, value);
    }

    public void hdel(String key, Object field) {
        template.opsForHash().delete(key, field);
    }

    public Map<Object, Object> hEntries(String key) {
        return template.opsForHash().entries(key);
    }

}
